package com.thomas.activeMQ;


import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**   
* @Description: 消息生产者
* @author thomas_liu  
* @date 2018年6月24日 下午7:39:27 
* @version V1.0   
*/
public class JMSProducer {
	//默认的连接用户名
	private static final String USERNAME=ActiveMQConnection.DEFAULT_USER;
	
	//默认的连接密码
	private static final String PASSWORD=ActiveMQConnection.DEFAULT_PASSWORD;
	
	//默认的连接地址
	private static final String BROKEURL=ActiveMQConnection.DEFAULT_BROKER_URL;
	
	//发送的消息数量
	private static final int SENDNUM= 10;
	
	public static void main(String[] args) throws Exception {
		
		//连接工厂
		ConnectionFactory connectionFactory;
		
		//连接
		Connection connection = null;
		
		//会话  接受或者发送消息的线程
		Session session;
		
		//消息的目的地
		Destination destination;
		
		//消息生产者
		MessageProducer messageProducer;
		
		//实例化连接工厂
		connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);
		
		try {
			//通过连接工厂获取连接
			connection = connectionFactory.createConnection();
			//启动连接
			connection.start();
			
			//创建Session
			session=connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			//创建消息队列
			destination=session.createQueue("FirstQueue1");
			//创建消息生产者
			messageProducer=session.createProducer(destination);
			//发送消息
			sendMessage(session, messageProducer);
			session.commit();
			
		} catch (JMSException e) {
			e.printStackTrace();
		}finally{
			if(connection!=null){
				try {
					connection.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		
		
		
	}
	
	/**
	 *发送消息 
	 *@param session
	 *@param messageProducer
	 *@throws Exception 
	 */
	public static void sendMessage(Session session,MessageProducer messageProducer) throws Exception{
		for(int i=0;i<SENDNUM;i++){
			TextMessage message = session.createTextMessage("ActiveMQ 发送的消息"+i);
			System.out.println("发送消息："+"ActiveMQ 发送的消息"+i);
			messageProducer.send(message);
		}
	}
	

}
